package com.ie.comment.sercurity.utiles;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 *
 *
 *
 **/

@Component
@Slf4j
public class RedisUtil {
    @Autowired
    private RedisTemplate<String , Object> redisTemplate;

    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        }
        catch (Exception e) {
            log.error("redis set error", e);
            return false;
        }
    }

    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public Object get(String key) {
        return key == null ? null :redisTemplate.opsForValue().get(key);
    }

    public void delete(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            }else {
                redisTemplate.delete(Arrays.asList(key));
            }
        }
    }

    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        }catch (Exception e) {
            log.error("redis hasKey error", e);
            return false;
        }
    }

    public void expire(String key, long redisExpiration) {
        if (key != null) {
            redisTemplate.expire(key, redisExpiration, TimeUnit.SECONDS);
        }else {
            log.error("redis expire error");

        }
    }
}
